#coding=utf8
from django.shortcuts import render, redirect, HttpResponse
from .lib.fun import *
from .models import *
from django.db.models import Q
from .settings import SEO
import xlsxwriter
import csv
import io
import json as json_lib

def excel(request):
    return setRenderResponse(request, 'excel.html')

def excelUpload(request):
    f = request.FILES.get('file')
    if not f:
        return HttpResponse(json.dumps({'status': 500, 'msg': 'Invalid Param'}), 'application/json')

    flag, url = UploadFile(f.name, f)
    if flag:
        return HttpResponse(json.dumps({'status': 200, 'url': url}), 'application/json')

    return HttpResponse(json.dumps({'status': 500, 'msg': 'Invalid Param'}), 'application/json')

def excelDisplay(request):
    excelUrl = request.GET.get('url')
    if GetFileSuffix(excelUrl) != '.xlsx':
        return render(request, '500.html')

    return setRenderResponse(request, 'excel.display.html', {'excelUrl': excelUrl})

def jsonEditor(request):
    data = {
        'seoTitle': 'Editor.js: Advanced Block-Style Rich Text Editor with Clean JSON Output',
        'seoKeywords': 'block-styled editor, rich text editor, JSON content, web editor, extensible editor, content blocks, web development, editor.js',
        'seoDescription': 'A powerful, extensible block-styled editor that provides clean JSON data output, enabling flexible content creation across web and mobile platforms with easy plugin integration.'
    }
    return setRenderResponse(request, 'json.editor.html', data)

def jsonFormat(request):
    data = {
        'seoTitle': 'Free Online JSON Formatter & Validator - Beautify and Minify JSON',
        'seoKeywords': 'JSON formatter, JSON validator, JSON beautifier, online JSON tool, JSON parser, JSON viewer, JSON editor, JSON pretty print, JSON formatter online',
        'seoDescription': 'Instantly format, validate, beautify, and minify your JSON data with our free online tool. No registration required. Real-time validation with error highlighting. Works directly in your browser for maximum speed and privacy.'
    }
    return setRenderResponse(request, 'json.html', data)

def imageEditor(request):
    data = {
        'seoTitle': 'Free Online Image Editor - Crop, Resize, Annotate [2025] | WebPhotoTools',
        'seoKeywords': 'crop image online, resize picture for web, add text to photo online, online watermark tool, blur background online, free online photo editor no sign up',
        'seoDescription': 'Edit images online for free! No signup needed. Resize, crop, add filters, text, watermarks, and shapes directly in your browser. Start editing now!'
    }
    return setRenderResponse(request, 'image.editor.html', data)

def markdownEditor(request):
    data = {
        'seoTitle': 'Free Online Markdown Editor with Live Preview - Write & Convert Markdown to HTML',
        'seoKeywords': 'markdown editor, markdown to html, online markdown editor, markdown preview, markdown converter, github flavored markdown, write markdown online',
        'seoDescription': 'Professional online Markdown editor with real-time HTML preview. Write, edit, and convert Markdown to HTML instantly. Supports GitHub Flavored Markdown with syntax highlighting. Free and fast!'
    }
    return setRenderResponse(request, 'markdown.editor.html', data)

def jsCompress(request):
    data = {
        'seoTitle': 'Free Online JavaScript Compressor & Minifier - Optimize Your JS Code',
        'seoKeywords': 'javascript compressor, js minifier, javascript optimizer, minify js online, compress javascript, beautify js, js code formatter, javascript tool',
        'seoDescription': 'Compress and minify JavaScript files online for free. Reduce file size by removing whitespace and comments. Also beautify and format JS code for better readability. No signup required!'
    }
    return setRenderResponse(request, 'js.compress.html', data)

def sqlFormat(request):
    data = {
        'seoTitle': 'Free Online SQL Formatter & Minifier - Beautify and Compress SQL',
        'seoKeywords': 'sql formatter, sql beautifier, sql minifier, format sql online, compress sql, sql pretty print, online sql tool',
        'seoDescription': 'Format and minify SQL queries online for free. Beautify complex SQL with proper indentation and syntax highlighting, or compress SQL by removing comments and extra whitespace. Fast, secure, and client-side.'
    }
    return setRenderResponse(request, 'sql.html', data)


def imageCompress(request):
    data = {
        'seoTitle': 'Free Online Image Compressor - Optimize JPEG, PNG, WebP Images',
        'seoKeywords': 'image compressor, compress images online, optimize images, reduce image size, image optimizer, jpeg compressor, png compressor, webp converter, image compression tool',
        'seoDescription': 'Compress and optimize images online for free. Reduce JPEG, PNG, WebP, and GIF file sizes while maintaining quality. Batch compression with format conversion. No signup required!'
    }
    return setRenderResponse(request, 'image.compress.html', data)


def base64Tool(request):
    data = {
        'seoTitle': 'Free Online Base64 Encoder & Decoder - Encode and Decode Base64 Text',
        'seoKeywords': 'base64 encoder, base64 decoder, online base64 tool, encode decode base64, base64 converter, text to base64, base64 to text, free base64 tool',
        'seoDescription': 'Free online Base64 encoder and decoder tool. Easily encode text to Base64 or decode Base64 to readable text. Fast, secure, and works directly in your browser. No registration required!'
    }
    return setRenderResponse(request, 'base64.html', data)

def imageEnhance(request):
    data = {
        'seoTitle': 'Free AI Image Enhancer - Upscale and Improve Image Quality Online',
        'seoKeywords': 'image enhancer, upscale image, image quality improvement, AI image enhancement, photo upscaling, image resolution increase, online image enhancer',
        'seoDescription': 'Enhance and upscale your images with AI technology. Improve image quality, increase resolution, and make blurry photos sharp. Free online tool with instant results.'
    }
    return setRenderResponse(request, 'image.enhance.html', data)

def imageEnhanceUpload(request):
    if request.method != 'POST':
        return HttpResponse(json.dumps({'status': 400, 'msg': 'Method not allowed'}), 'application/json')

    f = request.FILES.get('file')
    if not f:
        return HttpResponse(json.dumps({'status': 500, 'msg': 'No file provided'}), 'application/json')

    # 检查文件类型
    allowed_types = ['.jpg', '.jpeg', '.png', '.webp', '.bmp']
    file_suffix = GetFileSuffix(f.name.lower())
    if file_suffix not in allowed_types:
        return HttpResponse(json.dumps({'status': 500, 'msg': 'Invalid file type. Only JPG, PNG, WebP, and BMP are supported'}), 'application/json')

    # 检查文件大小 (限制10MB)
    if f.size > 10 * 1024 * 1024:
        return HttpResponse(json.dumps({'status': 500, 'msg': 'File size too large. Maximum 10MB allowed'}), 'application/json')

    flag, url = UploadFile(f.name, f)
    if flag:
        return HttpResponse(json.dumps({'status': 200, 'url': url, 'originalName': f.name}), 'application/json')

    return HttpResponse(json.dumps({'status': 500, 'msg': 'Upload failed'}), 'application/json')

def imageEnhanceProcess(request):
    if request.method != 'POST':
        return HttpResponse(json.dumps({'status': 400, 'msg': 'Method not allowed'}), 'application/json')

    import requests
    from PIL import Image
    import io
    import os
    from django.conf import settings

    image_url = request.POST.get('imageUrl')
    enhance_type = request.POST.get('enhanceType', 'upscale')  # upscale, denoise, sharpen
    scale_factor = int(request.POST.get('scaleFactor', 2))

    if not image_url:
        return HttpResponse(json.dumps({'status': 400, 'msg': 'No image URL provided'}), 'application/json')

    try:
        # 从URL下载图片
        if image_url.startswith('http'):
            response = requests.get(image_url, timeout=10)
            if response.status_code != 200:
                return HttpResponse(json.dumps({'status': 500, 'msg': 'Failed to download image'}), 'application/json')
            image_data = response.content
        else:
            # 本地文件路径处理
            file_path = image_url.replace(settings.STATIC_URL, settings.STATIC_ROOT + '/')
            if not os.path.exists(file_path):
                return HttpResponse(json.dumps({'status': 500, 'msg': 'Image file not found'}), 'application/json')
            with open(file_path, 'rb') as f:
                image_data = f.read()

        # 打开图片
        image = Image.open(io.BytesIO(image_data))

        # 转换为RGB格式(如果需要)
        if image.mode in ('RGBA', 'LA', 'P'):
            background = Image.new('RGB', image.size, (255, 255, 255))
            if image.mode == 'P':
                image = image.convert('RGBA')
            background.paste(image, mask=image.split()[-1] if image.mode in ('RGBA', 'LA') else None)
            image = background
        elif image.mode != 'RGB':
            image = image.convert('RGB')

        # 根据增强类型处理图片
        if enhance_type == 'upscale':
            # 简单的双线性插值放大
            new_size = (image.width * scale_factor, image.height * scale_factor)
            enhanced_image = image.resize(new_size, Image.LANCZOS)
        elif enhance_type == 'sharpen':
            # 锐化滤镜
            from PIL import ImageFilter
            enhanced_image = image.filter(ImageFilter.SHARPEN)
        elif enhance_type == 'denoise':
            # 降噪(使用模糊滤镜模拟)
            from PIL import ImageFilter
            enhanced_image = image.filter(ImageFilter.SMOOTH)
        else:
            enhanced_image = image

        # 保存处理后的图片
        output_buffer = io.BytesIO()
        enhanced_image.save(output_buffer, format='JPEG', quality=95)
        output_data = output_buffer.getvalue()

        # 生成唯一文件名并保存
        import hashlib
        import time
        hash_obj = hashlib.md5()
        hash_obj.update(output_data)
        hash_obj.update(str(time.time()).encode())
        filename = f"enhanced_{hash_obj.hexdigest()}.jpg"

        # 保存到上传目录
        upload_dir = os.path.join(settings.BASE_DIR, 'dist', 'upload', '0')
        os.makedirs(upload_dir, exist_ok=True)

        output_path = os.path.join(upload_dir, filename)
        with open(output_path, 'wb') as f:
            f.write(output_data)

        # 生成访问URL
        from core.settings import Host
        enhanced_url = f"{Host}{settings.STATIC_URL}upload/0/{filename}"

        return HttpResponse(json.dumps({
            'status': 200,
            'enhancedUrl': enhanced_url,
            'originalSize': f"{image.width}x{image.height}",
            'enhancedSize': f"{enhanced_image.width}x{enhanced_image.height}",
            'enhanceType': enhance_type
        }), 'application/json')

    except Exception as e:
        return HttpResponse(json.dumps({'status': 500, 'msg': f'Processing failed: {str(e)}'}), 'application/json')

def urlEncodeDecode(request):
    data = {
        'seoTitle': 'Free Online URL Encoder & Decoder - Encode and Decode URLs',
        'seoKeywords': 'url encoder, url decoder, online url tool, encode decode url, url converter, uri encoder, uri decoder, percent encoding, free url tool',
        'seoDescription': 'Free online URL encoder and decoder tool. Easily encode URLs for safe transmission or decode percent-encoded URLs. Fast, secure, and works directly in your browser. No registration required!'
    }
    return setRenderResponse(request, 'url.html', data)

def cookieFormat(request):
    # Cookie formatter page
    data = {
        'seoTitle': 'Free Online Cookie Formatter - Parse Cookie Header to JSON',
        'seoKeywords': 'cookie formatter, parse cookies, cookie to json, online cookie parser, http cookie tool',
        'seoDescription': 'Paste an HTTP Cookie header and instantly convert it to structured JSON. Decode URL-encoded values and copy the formatted result. 100% client-side and secure.'
    }
    return setRenderResponse(request, 'cookie.html', data)

def contact(request):
    return setRenderResponse(request, 'contact.html')

def contactSubmit(request):
    from core.lib.mail import Mail
    name = request.POST.get('name', '').strip()
    email = request.POST.get('email', '').strip()
    message = request.POST.get('message', '').strip()

    content = f'From {name}: ' + message
    subject = f'From {email} of tool.freefonts1001.com'
    Mail.sendMail(content, subject)

    return HttpResponse(json.dumps({'status': 200, 'msg': 'Success'}), 'application/json')

def jsonToExcel(request):
    """Convert JSON array data to Excel format and return as download"""
    try:
        if request.method != 'POST':
            return HttpResponse(json.dumps({'status': 400, 'msg': 'Method not allowed'}), 'application/json')

        json_data = request.POST.get('jsonData', '')
        if not json_data:
            return HttpResponse(json.dumps({'status': 400, 'msg': 'No JSON data provided'}), 'application/json')

        # Parse JSON data
        try:
            data = json_lib.loads(json_data)
        except json_lib.JSONDecodeError as e:
            return HttpResponse(json.dumps({'status': 400, 'msg': f'Invalid JSON: {str(e)}'}), 'application/json')

        # Check if data is an array
        if not isinstance(data, list):
            return HttpResponse(json.dumps({'status': 400, 'msg': 'JSON data must be an array format for export'}), 'application/json')

        if len(data) == 0:
            return HttpResponse(json.dumps({'status': 400, 'msg': 'JSON array is empty'}), 'application/json')

        # Get all unique keys from the first level of all objects
        headers = set()
        for item in data:
            if isinstance(item, dict):
                headers.update(item.keys())

        headers = list(headers)

        if len(headers) == 0:
            return HttpResponse(json.dumps({'status': 400, 'msg': 'No valid data structure found for export'}), 'application/json')

        # Create Excel file in memory
        output = io.BytesIO()
        workbook = xlsxwriter.Workbook(output, {'in_memory': True})
        worksheet = workbook.add_worksheet('JSON Data')

        # Add header format
        header_format = workbook.add_format({
            'bold': True,
            'bg_color': '#D7E4BC',
            'border': 1
        })

        # Cell format
        cell_format = workbook.add_format({
            'border': 1,
            'text_wrap': True
        })

        # Write headers
        for col, header in enumerate(headers):
            worksheet.write(0, col, header)

        # Write data rows
        for row, item in enumerate(data, 1):
            if isinstance(item, dict):
                for col, header in enumerate(headers):
                    value = item.get(header, '')
                    # Convert complex objects to string
                    if isinstance(value, (dict, list)):
                        value = json_lib.dumps(value, ensure_ascii=False)
                    worksheet.write(row, col, str(value))

        # Adjust column widths
        for col in range(len(headers)):
            worksheet.set_column(col, col, 20)

        workbook.close()
        output.seek(0)

        # Create response
        response = HttpResponse(
            output.getvalue(),
            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
        response['Content-Disposition'] = 'attachment; filename="json_data.xlsx"'

        return response

    except Exception as e:
        return HttpResponse(json.dumps({'status': 500, 'msg': f'Error: {str(e)}'}), 'application/json')

def jsonToCsv(request):
    """Convert JSON array data to CSV format and return as download"""
    try:
        if request.method != 'POST':
            return HttpResponse(json.dumps({'status': 400, 'msg': 'Method not allowed'}), 'application/json')

        json_data = request.POST.get('jsonData', '')
        if not json_data:
            return HttpResponse(json.dumps({'status': 400, 'msg': 'No JSON data provided'}), 'application/json')

        # Parse JSON data
        try:
            data = json_lib.loads(json_data)
        except json_lib.JSONDecodeError as e:
            return HttpResponse(json.dumps({'status': 400, 'msg': f'Invalid JSON: {str(e)}'}), 'application/json')

        # Check if data is an array
        if not isinstance(data, list):
            return HttpResponse(json.dumps({'status': 400, 'msg': 'JSON data must be an array format for export'}), 'application/json')

        if len(data) == 0:
            return HttpResponse(json.dumps({'status': 400, 'msg': 'JSON array is empty'}), 'application/json')

        # Get all unique keys from the first level of all objects
        headers = set()
        for item in data:
            if isinstance(item, dict):
                headers.update(item.keys())

        headers = list(headers)

        if len(headers) == 0:
            return HttpResponse(json.dumps({'status': 400, 'msg': 'No valid data structure found for export'}), 'application/json')

        # Create CSV in memory
        output = io.StringIO()
        writer = csv.writer(output)

        # Write header
        writer.writerow(headers)

        # Write data rows
        for item in data:
            if isinstance(item, dict):
                row = []
                for header in headers:
                    value = item.get(header, '')
                    # Convert complex objects to string
                    if isinstance(value, (dict, list)):
                        value = json_lib.dumps(value, ensure_ascii=False)
                    row.append(str(value))
                writer.writerow(row)

        # Create response
        response = HttpResponse(output.getvalue(), content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="json_data.csv"'

        return response

    except Exception as e:
        return HttpResponse(json.dumps({'status': 500, 'msg': f'Error: {str(e)}'}), 'application/json')

def setRenderResponse(request, tpl, data={}):
    from core.settings import Host
    data.update({
        'host': Host,
    });
    data.setdefault('updateTime', '')
    data.setdefault('filters', {'keyword': ''})

    if not data.get('seoTitle'):
        data['seoTitle'] = SEO['title']
    
    if not data.get('seoKeywords'):
        data['seoKeywords'] = SEO['keywords']

    if not data.get('seoDescription'):
        data['seoDescription'] = SEO['description']

    return render(request, tpl, data)


